#include "Fauxiliar.h"




void EliminarIndeseables(char**linea)
{
    int i=0;

    while((*linea)[i]!='\n')
    i++;

    (*linea)[i]='\0';
}

int getString(char** result, FILE* f)
{
    int chunksize = NUMCARACTERES;
    char *s;
    char *temp;
    int buffersize = chunksize+1;
    int ret = RES_OK;

    s = malloc(buffersize); /* get the first chunk */
    if (s == NULL) {
        return ERR_OUT_OF_MEMORY;
    }

    /* read the first chunk with standard library fgets */
    if (fgets(s, chunksize+1, f) == NULL) {
        ret = ERROR_OR_EOF;
    }
    else {
        while (strchr(s, '\n') == NULL && strchr(s, '\r') == NULL ) {
            buffersize += chunksize;
            temp = realloc(s, buffersize);
            if (temp == NULL) {
                free(s); /* clean up the previously allocated stuff */
                s = NULL;
                ret = ERR_OUT_OF_MEMORY;
                break;
            }
            else {
                s = temp;
                /*read into the zero byte that was the end of the previous chunk */
                if (fgets(s+buffersize-chunksize-1, chunksize+1, f) == NULL) {
                    break;
                }
            }
        }
    }

    /* Elimino los caracteres de retorno y nueva linea */

    EliminarIndeseables(&s);
    *result = s;

    return ret;
}

void BorrarLiteral(TAB ab,int mov)
{
    TLiteral lit;
    int error;


    AB_MoverCte(&ab,mov,&error);
    if (!error)
    {
        BorrarLiteral(ab,IZQ);
        AB_ElemCte(ab,&lit);
        Literal_Destruir(&lit);
        BorrarLiteral(ab,DER);
    }
}

void In_Order(TAB ab, int mov, void(*proceso)(TAB))
{
    int error;

    AB_MoverCte(&ab, mov, &error);
    if (!error)
    {
        In_Order(ab, IZQ, proceso);
        proceso(ab);
        In_Order(ab, DER, proceso);
    }
}

/* BORRAR LUEGO, ES SOLO PARA PRUEBA */
void MostrarLiteral(TAB ab)
{
    TLiteral lit;
    char* strLiteral;

    AB_ElemCte(ab, &lit);
    Literal_AString(&lit, &strLiteral);
    printf("%s", strLiteral);
}
